<template>
  <div class="container-header-margin content">
    <div class="back-button-container">
      <a-button class="back-button" @click="goBack">
        返回
      </a-button>
      <!-- 新增按钮组 -->
      <div class="button-group">
        <a-button @click="showQuitModal">退出团队</a-button>
        <a-button v-if="isLeader || isTutor" @click="showTransferModal">负责人转让</a-button>
        <a-button v-if="isLeader || isTutor" @click="updateUserTeamsHandler">编辑</a-button>
      </div>
    </div>
    <div class="team-details-page">
      <a-card :bordered="false">
        <header class="team-header">
          <h1 class="team-name">{{ teamName }}</h1>
          <div class="team-info">
            <span><trophy-outlined /> 项目类型: {{ competitionName }}</span>
            <span><team-outlined /> 立项编号: {{ teamCode }}</span>
          </div>
        </header>
        <main>
          <!-- 指导老师部分 -->
          <a-divider>指导老师</a-divider>
          <section class="tutors">
            <a-row :gutter="[16, 16]">
              <a-col :span="8" v-for="tutor in tutors" :key="tutor.id">
                <a-card class="member-card">
                  <div class="member">
                    <a-avatar :size="64" :src="tutor.avatar">
                      {{ tutor.name?.substring(0, 1) || 'T' }}
                    </a-avatar>
                    <div class="member-info">
                      <h3>{{ tutor.name }} <a-tag color="green">指导老师</a-tag></h3>
                      <p><bank-outlined /> {{ tutor.school || '未设置学校' }}</p>
                      <p><read-outlined /> {{ tutor.title || '未设置职称' }}</p>
                      <p v-if="tutor.phone || tutor.email">
                        <phone-outlined /> {{ tutor.phone || '' }}
                        <span style="margin: 0 5px">|</span>
                        <mail-outlined /> {{ tutor.email || '' }}
                      </p>
                      <p v-else><phone-outlined /> 未设置联系方式</p>
                    </div>
                  </div>
                </a-card>
              </a-col>
            </a-row>
            <a-empty v-if="!tutors.length" description="暂无指导老师信息" />
          </section>

          <a-modal
    v-model:visible="transferModalVisible"
    title="转让负责人"
    ok-text="确认转让"
    cancel-text="取消"
    @ok="handleTransferConfirm"
    @cancel="handleTransferCancel"
  >
    <div class="transfer-modal-content">
  
      
      <a-list :data-source="filteredMembers" bordered>
        <template #renderItem="{ item }">
          <a-list-item 
            :class="['member-item', { 'selected': selectedNewLeaderId === item.id }]"
            @click="handleSelectMember(item)"
          >
            <a-list-item-meta>
              <template #avatar>
                <a-avatar :src="item.avatar">{{ item.name?.charAt(0) }}</a-avatar>
              </template>
              <template #title>
                {{ item.name }}
                <a-tag v-if="item.isLeader" color="blue">现任队长</a-tag>
              </template>
              <template #description>
                <p><bank-outlined /> {{ item.school || '未设置学校' }}</p>
                <p><mail-outlined /> {{ item.email || '未设置邮箱' }}</p>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </a-modal>


    <!-- 新增编辑团队信息模态框 -->
  <a-modal
    v-model:visible="editModalVisible"
    title="编辑团队信息"
    ok-text="保存"
    cancel-text="取消"
    @ok="handleEditSubmit"
    @cancel="editModalVisible = false"
  >
    <a-form layout="vertical">
      <a-form-item label="团队名称">
        <a-input v-model:value="editForm.name" placeholder="请输入团队名称" />
      </a-form-item>
      <a-divider>团队成员</a-divider>
      <div class="info-list">
        <div v-for="member in allMembers" :key="member.id" class="info-item">
          {{ member.name }}
          <a-tag v-if="member.isLeader" color="blue">队长</a-tag>
          <a-button
            v-if="!member.isLeader"
            type="link"
            danger
            @click="() => handleDeleteMemberConfirm(member.id, member.isTeacher)"
          >
            剔除
          </a-button>
        </div>
        <a-empty v-if="!allMembers.length" description="暂无成员" />
      </div>
    </a-form>
  </a-modal>
          <!-- 队长和团队成员部分 -->
          <a-divider>团队成员</a-divider>
          <section class="members">
            <a-empty v-if="!allMembers.length" description="暂无成员信息" />
            <a-row :gutter="[16, 16]" v-else>
              <a-col :span="8" v-for="member in allMembers" :key="member.id">
                <a-card class="member-card">
                  <div class="member">
                    <a-avatar :size="64" :src="member.avatar">
                      {{ member.name?.substring(0, 1) || (member.isLeader ? 'L' : 'U') }}
                    </a-avatar>
                    <div class="member-info">
                      <h3>{{ member.name }} <a-tag v-if="member.isLeader" color="blue">队长</a-tag></h3>
                      <p><bank-outlined /> {{ member.school || '未设置学校' }}</p>
                      <p><read-outlined /> {{ member.major || '未设置专业' }}</p>
                      <p v-if="member.phone || member.email">
                        <phone-outlined /> {{ member.phone || '' }}
                        <span style="margin: 0 5px">|</span>
                        <mail-outlined /> {{ member.email || '' }}
                      </p>
                      <p v-else><phone-outlined /> 未设置联系方式</p>
                    </div>
                  </div>
                </a-card>
              </a-col>
            </a-row>
          </section>
        </main>
      </a-card>
    </div>
  </div>

</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getTeamDetail, quitTeam, transferLeader, updateUserTeams, deleteTeamMember } from '@/apis';
import { message, Modal } from 'ant-design-vue';
import {
  TrophyOutlined,
  TeamOutlined,
  BankOutlined,
  ReadOutlined,
  PhoneOutlined,
  MailOutlined
} from '@ant-design/icons-vue';
import { useNuxtApp } from '#app';

const route = useRoute();
const router = useRouter();
const teamId = computed(() => route.query.teamId);

const teamName = ref('');
const competitionName = ref('');
const teamCode = ref('');
const leader = ref({});
const tutors = ref([]);
const members = ref([]);
const currentUserId = ref(null);
const transferModalVisible = ref(false);
const selectedNewLeaderId = ref(null);
const searchKeyword = ref('');
const editModalVisible = ref(false);
const editForm = ref({
  name: '',
});

const editFormData = ref({
  teamName: '',
  competitionName: '',
  teamCode: '',
  tutors: [],
  members: []
});

// 获取当前用户信息
const fetchUserInfo = async () => {
  const { $myFetch } = useNuxtApp();
  try {
    const res = await $myFetch('/api/user/getUserInfo', { method: 'post' });
    if (res.code === 200) {
      currentUserId.value = res.data.id;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 合并队长和团队成员
const allMembers = computed(() => {
  if (leader.value.id) {
    return [
      { ...leader.value, isLeader: true },
      ...members.value.filter(member => member.id !== leader.value.id)
    ];
  }
  return members.value;
});
// 判断当前用户是否是负责人
const isLeader = computed(() => {
  return leader.value.id === currentUserId.value;
});

const fetchTeamDetail = async () => {
  if (!teamId.value) {
    message.error('团队ID不存在');
    router.push('/user');
    return;
  }

  try {
    const res = await getTeamDetail(teamId.value);
    if (res.code === 200) {
      const data = res.data;
      teamName.value = data.name;
      competitionName.value = data.raceInfoVo.sonName;
      teamCode.value = data.projectCode;
      leader.value = data.leaderInfo || {};
      tutors.value = data.teacherInfoBOList || [];
      members.value = data.memberInfoBOList || [];
    }
  } catch (error) {
    console.error('获取团队详情失败:', error);
    message.error('获取团队详情失败，请稍后重试');
    router.push('/user');
  }
};

// 退出团队方法
const quitTeamHandler = async () => {
  try {
    const res = await quitTeam(teamId.value);
    if (res.code === 200) {
      message.success('退出团队成功');
      router.push('/user');
    } else {
      message.error('退出团队失败');
    }
  } catch (error) {
    console.error('退出团队失败:', error);
    message.error('退出团队失败，请稍后重试');
  }
};
// 显示退出团队确认对话框
const showQuitModal = () => {
  

  Modal.confirm({
    title: '确认退出团队',
    content: '您确定要退出该团队吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: quitTeamHandler
  });
};
/* // 负责人转让方法
const transferLeaderHandler = async () => {
  // 这里可以添加选择新负责人的逻辑，假设新负责人的 ID 为 newLeaderId
  const newLeaderId = 1; // 示例 ID，需要根据实际情况修改
  try {
    const res = await transferLeader(teamId.value, newLeaderId);
    if (res.code === 200) {
      message.success('负责人转让成功');
      // 重新获取团队详情
      fetchTeamDetail();
    } else {
      message.error('负责人转让失败');
    }
  } catch (error) {
    console.error('负责人转让失败:', error);
    message.error('负责人转让失败，请稍后重试');
  }
}; */
// 负责人转让方法
const transferLeaderHandler = async (newLeaderId) => {
  try {
    const res = await transferLeader(teamId.value, newLeaderId);
    if (res.code === 200) {
      message.success('负责人转让成功');
      // 重新获取团队详情
      fetchTeamDetail();
    } else {
      message.error('负责人转让失败');
    }
  } catch (error) {
    console.error('负责人转让失败:', error);
    message.error('负责人转让失败，请稍后重试');
  }
};
// 显示负责人转让对话框
const showTransferModal2 = () => {
  if (!isLeader.value) {
    message.warning('您不是团队负责人，无法转让');
    return;
  }
  // 过滤掉当前负责人
  const candidateMembers = allMembers.value.filter(member => member.id !== currentUserId.value);
  
  if (candidateMembers.length === 0) {
    message.warning('没有可转让的成员');
    return;
  }

  Modal.confirm({
    title: '选择新负责人',
    content: `
      <a-select
        style="width: 100%"
        placeholder="请选择新负责人"
        :options="candidateMembers.map(member => ({
          label: member.name,
          value: member.id
        }))"
      />
    `,
    okText: '确定',
    cancelText: '取消',
    onOk: (e) => {
      const newLeaderId = e.target.previousSibling.querySelector('.ant-select-selection-item')?.dataset?.value;
      if (newLeaderId) {
        transferLeaderHandler(newLeaderId);
      } else {
        message.warning('请先选择新负责人');
      }
    }
  });
};

// 编辑团队信息方法
const updateUserTeamsHandler = async () => {
  if (!isLeader.value) {
    message.warning('您不是团队负责人，无法编辑');
    return;
  }
  // 初始化表单数据
  editForm.value.name = teamName.value;
  editModalVisible.value = true;
};

// 新增提交处理方法
const handleEditSubmit = async () => {
  try {
    const res = await updateUserTeams({ teamId: teamId.value }, {
      name: editForm.value.name
      
    });
    
    if (res.code === 200) {
      message.success('团队信息更新成功');
      teamName.value = editForm.value.name;
      editModalVisible.value = false;
    } else {
      message.error(res.msg || '更新失败');
    }
  } catch (error) {
    console.error('更新失败:', error);
    message.error('更新失败，请稍后重试');
  }
};

// 处理剔除成员
const handleDeleteMember = async (userId, isTeacher) => {
  try {
    const res = await deleteTeamMember(teamId.value, userId, isTeacher);
    if (res.code === 200) {
      message.success('剔除成员成功');
      fetchTeamDetail(); // 重新获取团队详情
    } else {
      message.error(res.msg || '剔除成员失败');
    }
  } catch (error) {
    console.error('剔除成员失败:', error);
    message.error('剔除成员失败，请稍后重试');
  }
};

// 处理剔除成员确认
const handleDeleteMemberConfirm = (userId, isTeacher) => {
  Modal.confirm({
    title: '确认剔除成员',
    content: '您确定要剔除该成员吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => handleDeleteMember(userId, isTeacher)
  });
};

// 计算过滤后的成员列表
const filteredMembers = computed(() => {
  return allMembers.value
    .filter(member => 
      !member.isLeader && 
      member.name?.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
    .map(member => ({
      ...member,
      isCurrent: member.id === currentUserId.value
    }));
});

// 修改显示转让弹窗方法
const showTransferModal = () => {
  
  if (filteredMembers.value.length === 0) {
    message.warning('没有可转让的成员');
    return;
  }
  
  transferModalVisible.value = true;
  selectedNewLeaderId.value = null;
  searchKeyword.value = '';
};

// 处理成员选择
const handleSelectMember = (member) => {
  selectedNewLeaderId.value = member.id;
};

// 处理确认转让
const handleTransferConfirm = async () => {
  if (!selectedNewLeaderId.value) {
    message.warning('请先选择新负责人');
    return;
  }

  try {
    const res = await transferLeader(teamId.value, selectedNewLeaderId.value);
    if (res.code === 200) {
      message.success('负责人转让成功');
      transferModalVisible.value = false;
      fetchTeamDetail();
    } else {
      message.error(res.msg || '负责人转让失败');
    }
  } catch (error) {
    console.error('转让失败:', error);
    message.error('转让请求失败，请稍后重试');
  }
};

// 处理取消转让
const handleTransferCancel = () => {
  transferModalVisible.value = false;
  selectedNewLeaderId.value = null;
};
// 显示编辑模态框
const showEditModal = () => {
  editModalVisible.value = true;
};




const goBack = () => {
  router.back();
};

onMounted(() => {
  fetchUserInfo();
  fetchTeamDetail();
});
</script>

<style scoped>
.container-header-margin {
  position: relative;
  padding: 20px;
}

.back-button-container {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-button {
  background-color: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s, color 0.3s;
}

.back-button:hover {
  background-color: #e0e0e0;
  color: #000;
}

.button-group {
  display: flex;
  gap: 10px;
}

.team-details-page {
  padding-top: 10px;
}

.team-header {
  margin-bottom: 24px;
  background: linear-gradient(135deg, #6a82fb 0%, #fc5c7d 100%);
  padding: 20px;
  border-radius: 8px;
  color: white;
}

header h1 {
  font-size: 24px;
  margin-bottom: 16px;
}

.team-info {
  display: flex;
  gap: 24px;
  color: #fff;
}

.team-info span {
  display: flex;
  align-items: center;
  gap: 8px;
}

.members,
.tutors {
  margin-top: 24px;
}

.member-card {
  transition: all 0.3s;
}

.member-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.member {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.member-info {
  flex: 1;
}

.member-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.member-info p {
  margin: 4px 0;
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
}
.transfer-modal-content {
  max-height: 60vh;
  overflow-y: auto;
}

.member-item {
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.member-item:hover {
  background-color: #f5f5f5;
}

.member-item.selected {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

:deep(.ant-list-item-meta-title) {
  display: flex;
  align-items: center;
  gap: 8px;
}
.info-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.info-item {
  padding: 8px;
  margin: 4px 0;
  background-color: #fafafa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>